<?php

namespace app\api\model;

class VolleyDesc extends Common
{
    static public function index($user_id, $money, $remark, $reward = 0, $gift = 0)
    {
        $User = new User;
        $Self = new VolleyDesc;

        $money = changefloor($money);
        $state = false;

        $userinfo = $User->master()->where(['id' => $user_id])->find();
        $current_balance_real = $current_balance = $reward ? ($userinfo['volley'] + $money) : ($userinfo['volley'] - $money);
        $current_balance_gift = $userinfo['volley_gift'];
        if ($gift) {
            $current_balance_gift = $reward ? ($userinfo['volley_gift'] + $money) : ($userinfo['volley_gift'] - $money);
        } else {
            $real_volley = $userinfo['volley'] - $userinfo['volley_gift'];
            $current_balance_real = 0;
            if (!$reward) {
                $current_balance_real = $real_volley - $money;
            }
        }

        if ($money > 0 && $current_balance >= 0 && $current_balance_gift >= 0 && $current_balance_real >= 0) {
            $method = $reward ? 'setInc' : 'setDec';

            $User->where(['id' => $user_id])->$method('volley', $money);
            if ($gift) {
                $User->where(['id' => $user_id])->$method('volley_gift', $money);
            }

            $Self->create([
                'user_id' => $user_id,
                'content' => $remark . ($gift?' 赠送金币':''),
                'price' => $money,
                'types' => $reward,
                'balance' => $current_balance,
                'time' => time()
            ]);
            $state = true;

            if (!$reward) {
                // 用户消费统计
                UserData::createData($user_id, $money, 'consume');
            }
        }
        return $state;
    }
    static public function beans($user_id, $money, $remark, $reward = 0, $gift = 0)
    {
        $User = new User;
        $Self = new VolleyDesc;

        $money = changefloor($money);
        $state = false;

        $userinfo = $User->master()->where(['id' => $user_id])->find();
        $current_balance = $reward ? ($userinfo['beans'] + $money) : ($userinfo['beans'] - $money);

        if ($money > 0 && $current_balance >= 0) {
            $method = $reward ? 'setInc' : 'setDec';

            $User->where(['id' => $user_id])->$method('beans', $money);

            $Self->create([
                'user_id' => $user_id,
                'content' => $remark,
                'price' => $money,
                'types' => $reward,
                'balance' => $current_balance,
                'desc' => 2,
                'time' => time()
            ]);
            $state = true;

            if (!$reward) {
                // 用户消费统计
                UserData::createData($user_id, $money, 'consume');
            }
        }
        return $state;
    }
}
